{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div align=\"center\">\n",
    "\n",
    "<img src=\"https://upload.wikimedia.org/wikipedia/commons/1/10/PyTorch_logo_icon.svg\" width=\"200\" alt=\"PyTorch\">\n",
    "\n",
    "\n",
    "\n",
    "# OpenEnv: Production RL Made Simple\n",
    "\n",
    "### *From \"Hello World\" to RL Training in 5 Minutes* ✨\n",
    "\n",
    "---\n",
    "\n",
    "**What if RL environments were as easy to use as REST APIs?**\n",
    "\n",
    "That's OpenEnv. Type-safe. Isolated. Production-ready. 🎯\n",
    "\n",
    "[![GitHub](https://img.shields.io/badge/GitHub-meta--pytorch%2FOpenEnv-blue?logo=github)](https://github.com/meta-pytorch/OpenEnv)\n",
    "[![License](https://img.shields.io/badge/License-BSD%203--Clause-green.svg)](https://opensource.org/licenses/BSD-3-Clause)\n",
    "[![PyTorch](https://img.shields.io/badge/PyTorch-EE4C2C?logo=pytorch&logoColor=white)](https://pytorch.org/)\n",
    "\n",
    "Author: [Sanyam Bhutani](http://twitter.com/bhutanisanyam1/)\n",
    "\n",
    "</div>\n",
    "\n",
    "\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## Why OpenEnv?\n",
    "\n",
    "Let's take a trip down memory lane:\n",
    "\n",
    "It's 2016, RL is popular. You read some papers, it looks promising. \n",
    "\n",
    "But in real world: Cartpole is the best you can run on a gaming GPU. \n",
    "\n",
    "What do you do beyond Cartpole?\n",
    "\n",
    "Fast-forward to 2025, GRPO is awesome and this time it's not JUST in theory, it works well in practise and is really here!\n",
    "\n",
    "The problem still remains, how do you take these RL algorithms and take them beyond Cartpole?\n",
    "\n",
    "A huge part of RL is giving your algorithms environment access to learn. \n",
    "\n",
    "We are excited to introduce an Environment Spec for adding Open Environments for RL Training. This will allow you to focus on your experiments and allow everyone to bring their environments.\n",
    "\n",
    "Focus on experiments, use OpenEnvironments, and build agents that go beyond Cartpole on a single spec.\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 📋 What You'll Learn\n",
    "\n",
    "<table>\n",
    "<tr>\n",
    "<td width=\"50%\">\n",
    "\n",
    "**🎯 Part 1-2: The Fundamentals**\n",
    "- ⚡ RL in 60 seconds\n",
    "- 🤔 Why existing solutions fall short\n",
    "- 💡 The OpenEnv solution\n",
    "\n",
    "</td>\n",
    "<td width=\"50%\">\n",
    "\n",
    "**🏗️ Part 3-5: The Architecture**\n",
    "- 🔧 How OpenEnv works\n",
    "- 🔍 Exploring real code\n",
    "- 🎮 OpenSpiel integration example\n",
    "\n",
    "</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td width=\"50%\">\n",
    "\n",
    "**🎮 Part 6-8: Hands-On Demo**\n",
    "- 🔌 Use existing OpenSpiel environment\n",
    "- 🤖 Test 4 different policies\n",
    "- 👀 Watch learning happen live\n",
    "\n",
    "</td>\n",
    "<td width=\"50%\">\n",
    "\n",
    "**🔧 Part 9-10: Going Further**\n",
    "- 🎮 Switch to other OpenSpiel games\n",
    "- ✨ Build your own integration\n",
    "- 🌐 Deploy to production\n",
    "\n",
    "</td>\n",
    "</tr>\n",
    "</table>\n",
    "\n",
    "> 💡 **Pro Tip**: This notebook is designed to run top-to-bottom in Google Colab with zero setup!\n",
    ">\n",
    "> ⏱️ **Time**: ~5 minutes | 📊 **Difficulty**: Beginner-friendly | 🎯 **Outcome**: Production-ready RL knowledge\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## 📑 Table of Contents\n",
    "\n",
    "<div style=\"background-color: rgba(128, 128, 128, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0; border: 1px solid rgba(128, 128, 128, 0.2);\">\n",
    "\n",
    "**Quick Navigation** - Click any section to jump right there! 🎯\n",
    "\n",
    "### Foundation\n",
    "- [Part 1: RL in 60 Seconds ⏱️](#part-1)\n",
    "- [Part 2: The Problem with Traditional RL 😤](#part-2)\n",
    "- [Part 3: Setup 🛠️](#part-3)\n",
    "\n",
    "### Architecture\n",
    "- [Part 4: The OpenEnv Pattern 🏗️](#part-4)\n",
    "- [Part 5: Example Integration - OpenSpiel 🎮](#part-5)\n",
    "\n",
    "### Hands-On Demo\n",
    "- [Part 6: Interactive Demo 🎮](#part-6)\n",
    "- [Part 7: Four Policies 🤖](#part-7)\n",
    "- [Part 8: Policy Competition! 🏆](#part-8)\n",
    "\n",
    "### Advanced\n",
    "- [Part 9: Using Real OpenSpiel 🎮](#part-9)\n",
    "- [Part 10: Create Your Own Integration 🛠️](#part-10)\n",
    "\n",
    "### Wrap Up\n",
    "- [Summary: Your Journey 🎓](#summary)\n",
    "- [Resources 📚](#resources)\n",
    "\n",
    "</div>\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "# Part 1: RL in 60 Seconds ⏱️\n",
    "\n",
    "<div style=\"background-color: rgba(128, 128, 128, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0; border: 1px solid rgba(128, 128, 128, 0.2);\">\n",
    "\n",
    "**Reinforcement Learning is simpler than you think.**\n",
    "\n",
    "It's just a loop:\n",
    "\n",
    "```python\n",
    "while not done:\n",
    "    observation = environment.observe()\n",
    "    action = policy.choose(observation)\n",
    "    reward = environment.step(action)\n",
    "    policy.learn(reward)\n",
    "```\n",
    "\n",
    "That's it. That's RL.\n",
    "\n",
    "</div>\n",
    "\n",
    "Let's see it in action:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "🎲 ========================================================== 🎲\n",
      "   Number Guessing Game - The Simplest RL Example\n",
      "🎲 ========================================================== 🎲\n",
      "\n",
      "🎯 I'm thinking of a number between 1 and 10...\n",
      "💭 You have 3 guesses. Let's see how random guessing works!\n",
      "\n",
      "💭 Guess #1: 2 → ❄️  Cold! (far)\n",
      "💭 Guess #2: 10 → 🎉 Correct! +10 points\n",
      "\n",
      "==============================================================\n",
      "💡 This is RL: Observe → Act → Reward → Repeat\n",
      "   But this policy is terrible! It doesn't learn from rewards.\n",
      "==============================================================\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "\n",
    "print(\"🎲 \" + \"=\"*58 + \" 🎲\")\n",
    "print(\"   Number Guessing Game - The Simplest RL Example\")\n",
    "print(\"🎲 \" + \"=\"*58 + \" 🎲\")\n",
    "\n",
    "# Environment setup\n",
    "target = random.randint(1, 10)\n",
    "guesses_left = 3\n",
    "\n",
    "print(f\"\\n🎯 I'm thinking of a number between 1 and 10...\")\n",
    "print(f\"💭 You have {guesses_left} guesses. Let's see how random guessing works!\\n\")\n",
    "\n",
    "# The RL Loop - Pure random policy (no learning!)\n",
    "while guesses_left > 0:\n",
    "    # Policy: Random guessing (no learning yet!)\n",
    "    guess = random.randint(1, 10)\n",
    "    guesses_left -= 1\n",
    "    \n",
    "    print(f\"💭 Guess #{3-guesses_left}: {guess}\", end=\" → \")\n",
    "    \n",
    "    # Reward signal (but we're not using it!)\n",
    "    if guess == target:\n",
    "        print(\"🎉 Correct! +10 points\")\n",
    "        break\n",
    "    elif abs(guess - target) <= 2:\n",
    "        print(\"🔥 Warm! (close)\")\n",
    "    else:\n",
    "        print(\"❄️  Cold! (far)\")\n",
    "else:\n",
    "    print(f\"\\n💔 Out of guesses. The number was {target}.\")\n",
    "\n",
    "print(\"\\n\" + \"=\"*62)\n",
    "print(\"💡 This is RL: Observe → Act → Reward → Repeat\")\n",
    "print(\"   But this policy is terrible! It doesn't learn from rewards.\")\n",
    "print(\"=\"*62 + \"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "<a id=\"part-2\"></a>\n",
    "# Part 2: The Problem with Traditional RL 😤\n",
    "\n",
    "<div style=\"background-color: rgba(248, 205, 16, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0; border: 1px solid rgba(248, 205, 16, 0.1);\">\n",
    "\n",
    "## 🤔 Why Can't We Just Use OpenAI Gym?\n",
    "\n",
    "Good question! Gym is great for research, but production needs more...\n",
    "\n",
    "</div>\n",
    "\n",
    "<table>\n",
    "<tr>\n",
    "<th>Challenge</th>\n",
    "<th>Traditional Approach</th>\n",
    "<th>OpenEnv Solution</th>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Type Safety</b></td>\n",
    "<td>❌ <code>obs[0][3]</code> - what is this?</td>\n",
    "<td>✅ <code>obs.info_state</code> - IDE knows!</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Isolation</b></td>\n",
    "<td>❌ Same process (can crash your training)</td>\n",
    "<td>✅ Docker containers (fully isolated)</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Deployment</b></td>\n",
    "<td>❌ \"Works on my machine\" 🤷</td>\n",
    "<td>✅ Same container everywhere 🐳</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Scaling</b></td>\n",
    "<td>❌ Hard to distribute</td>\n",
    "<td>✅ Deploy to Kubernetes ☸️</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Language</b></td>\n",
    "<td>❌ Python only</td>\n",
    "<td>✅ Any language (HTTP API) 🌐</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Debugging</b></td>\n",
    "<td>❌ Cryptic numpy errors</td>\n",
    "<td>✅ Clear type errors 🐛</td>\n",
    "</tr>\n",
    "</table>\n",
    "\n",
    "<div style=\"background-color: #d4edda; padding: 20px; border-left: 5px solid #28a745; margin: 20px 0;\">\n",
    "\n",
    "## 💡 The OpenEnv Philosophy\n",
    "\n",
    "**\"RL environments should be like microservices\"**\n",
    "\n",
    "Think of it like this: You don't run your database in the same process as your web server, right? Same principle!\n",
    "\n",
    "- 🔒 **Isolated**: Run in containers (security + stability)\n",
    "- 🌐 **Standard**: HTTP API, works everywhere\n",
    "- 📦 **Versioned**: Docker images (reproducibility!)\n",
    "- 🚀 **Scalable**: Deploy to cloud with one command\n",
    "- 🛡️ **Type-safe**: Catch bugs before they happen\n",
    "- 🔄 **Portable**: Works on Mac, Linux, Windows, Cloud\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The Architecture\n",
    "\n",
    "```\n",
    "┌────────────────────────────────────────────────────────────┐\n",
    "│  YOUR TRAINING CODE                                        │\n",
    "│                                                            │\n",
    "│  env = OpenSpielEnv(...)        ← Import the client      │\n",
    "│  result = env.reset()           ← Type-safe!             │\n",
    "│  result = env.step(action)      ← Type-safe!             │\n",
    "│                                                            │\n",
    "└─────────────────┬──────────────────────────────────────────┘\n",
    "                  │\n",
    "                  │  HTTP/JSON (Language-Agnostic)\n",
    "                  │  POST /reset, POST /step, GET /state\n",
    "                  │\n",
    "┌─────────────────▼──────────────────────────────────────────┐\n",
    "│  DOCKER CONTAINER                                          │\n",
    "│                                                            │\n",
    "│  ┌──────────────────────────────────────────────┐         │\n",
    "│  │  FastAPI Server                              │         │\n",
    "│  │  └─ Environment (reset, step, state)         │         │\n",
    "│  │     └─ Your Game/Simulation Logic            │         │\n",
    "│  └──────────────────────────────────────────────┘         │\n",
    "│                                                            │\n",
    "│  Isolated • Reproducible • Secure                          │\n",
    "└────────────────────────────────────────────────────────────┘\n",
    "```\n",
    "\n",
    "<div style=\"background-color: #e7f3ff; padding: 15px; border-left: 5px solid #0366d6; margin: 20px 0;\">\n",
    "\n",
    "**🎯 Key Insight**: You never see HTTP details - just clean Python methods!\n",
    "\n",
    "```python\n",
    "env.reset()    # Under the hood: HTTP POST to /reset\n",
    "env.step(...)  # Under the hood: HTTP POST to /step\n",
    "env.state()    # Under the hood: HTTP GET to /state\n",
    "```\n",
    "\n",
    "The magic? OpenEnv handles all the plumbing. You focus on RL! ✨\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "# Part 3: Setup 🛠️\n",
    "\n",
    "<div style=\"background-color: #f8f9fa; padding: 15px; border-radius: 5px; margin: 20px 0;\">\n",
    "\n",
    "**Running in Colab?** This cell will clone OpenEnv and install dependencies automatically.\n",
    "\n",
    "**Running locally?** Make sure you're in the OpenEnv directory.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "💻 Running locally - Nice!\n",
      "✅ Using local OpenEnv installation\n",
      "\n",
      "🚀 Ready to explore OpenEnv and build amazing things!\n",
      "💡 Tip: Run cells top-to-bottom for the best experience.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Detect environment\n",
    "try:\n",
    "    import google.colab\n",
    "    IN_COLAB = True\n",
    "    print(\"🌐 Running in Google Colab - Perfect!\")\n",
    "except ImportError:\n",
    "    IN_COLAB = False\n",
    "    print(\"💻 Running locally - Nice!\")\n",
    "\n",
    "if IN_COLAB:\n",
    "    print(\"\\n📦 Cloning OpenEnv repository...\")\n",
    "    !git clone https://github.com/meta-pytorch/OpenEnv.git > /dev/null 2>&1\n",
    "    %cd OpenEnv\n",
    "    \n",
    "    print(\"📚 Installing dependencies (this takes ~10 seconds)...\")\n",
    "    !pip install -q fastapi uvicorn requests\n",
    "    \n",
    "    import sys\n",
    "    sys.path.insert(0, './src')\n",
    "    print(\"\\n✅ Setup complete! Everything is ready to go! 🎉\")\n",
    "else:\n",
    "    import sys\n",
    "    from pathlib import Path\n",
    "    sys.path.insert(0, str(Path.cwd().parent / 'src'))\n",
    "    print(\"✅ Using local OpenEnv installation\")\n",
    "\n",
    "print(\"\\n🚀 Ready to explore OpenEnv and build amazing things!\")\n",
    "print(\"💡 Tip: Run cells top-to-bottom for the best experience.\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "<a id=\"part-4\"></a>\n",
    "# Part 4: The OpenEnv Pattern 🏗️\n",
    "\n",
    "<div style=\"background-color: #f0f7ff; padding: 20px; border-radius: 10px; margin: 20px 0;\">\n",
    "\n",
    "## Every OpenEnv Environment Has 3 Components:\n",
    "\n",
    "```\n",
    "src/envs/your_env/\n",
    "├── 📝 models.py          ← Type-safe contracts\n",
    "│                           (Action, Observation, State)\n",
    "│\n",
    "├── 📱 client.py          ← What YOU import\n",
    "│                           (HTTPEnvClient implementation)\n",
    "│\n",
    "└── 🖥️  server/\n",
    "    ├── environment.py    ← Game/simulation logic\n",
    "    ├── app.py            ← FastAPI server\n",
    "    └── Dockerfile        ← Container definition\n",
    "```\n",
    "\n",
    "</div>\n",
    "\n",
    "Let's explore the actual OpenEnv code to see how this works:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "======================================================================\n",
      "   🧩 OPENENV CORE ABSTRACTIONS\n",
      "======================================================================\n",
      "\n",
      "🖥️  SERVER SIDE (runs in Docker):\n",
      "\n",
      "    class Environment(ABC):\n",
      "        '''Base class for all environment implementations'''\n",
      "        \n",
      "        @abstractmethod\n",
      "        def reset(self) -> Observation:\n",
      "            '''Start new episode'''\n",
      "        \n",
      "        @abstractmethod\n",
      "        def step(self, action: Action) -> Observation:\n",
      "            '''Execute action, return observation'''\n",
      "        \n",
      "        @property\n",
      "        def state(self) -> State:\n",
      "            '''Get episode metadata'''\n",
      "\n",
      "📱 CLIENT SIDE (your training code):\n",
      "\n",
      "    class HTTPEnvClient(ABC):\n",
      "        '''Base class for HTTP clients'''\n",
      "        \n",
      "        def reset(self) -> StepResult:\n",
      "            # HTTP POST /reset\n",
      "        \n",
      "        def step(self, action) -> StepResult:\n",
      "            # HTTP POST /step\n",
      "        \n",
      "        def state(self) -> State:\n",
      "            # HTTP GET /state\n",
      "\n",
      "======================================================================\n",
      "\n",
      "✨ Same interface on both sides - communication via HTTP!\n",
      "🎯 You focus on RL, OpenEnv handles the infrastructure.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Import OpenEnv's core abstractions\n",
    "from core.env_server import Environment, Action, Observation, State\n",
    "from core.http_env_client import HTTPEnvClient\n",
    "\n",
    "print(\"=\"*70)\n",
    "print(\"   🧩 OPENENV CORE ABSTRACTIONS\")\n",
    "print(\"=\"*70)\n",
    "\n",
    "print(\"\"\"\n",
    "🖥️  SERVER SIDE (runs in Docker):\n",
    "\n",
    "    class Environment(ABC):\n",
    "        '''Base class for all environment implementations'''\n",
    "        \n",
    "        @abstractmethod\n",
    "        def reset(self) -> Observation:\n",
    "            '''Start new episode'''\n",
    "        \n",
    "        @abstractmethod\n",
    "        def step(self, action: Action) -> Observation:\n",
    "            '''Execute action, return observation'''\n",
    "        \n",
    "        @property\n",
    "        def state(self) -> State:\n",
    "            '''Get episode metadata'''\n",
    "\n",
    "📱 CLIENT SIDE (your training code):\n",
    "\n",
    "    class HTTPEnvClient(ABC):\n",
    "        '''Base class for HTTP clients'''\n",
    "        \n",
    "        def reset(self) -> StepResult:\n",
    "            # HTTP POST /reset\n",
    "        \n",
    "        def step(self, action) -> StepResult:\n",
    "            # HTTP POST /step\n",
    "        \n",
    "        def state(self) -> State:\n",
    "            # HTTP GET /state\n",
    "\"\"\")\n",
    "\n",
    "print(\"=\"*70)\n",
    "print(\"\\n✨ Same interface on both sides - communication via HTTP!\")\n",
    "print(\"🎯 You focus on RL, OpenEnv handles the infrastructure.\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "# Part 5: Example Integration - OpenSpiel 🎮\n",
    "\n",
    "<div style=\"background-color: #fff3e0; padding: 20px; border-radius: 10px; margin: 20px 0;\">\n",
    "\n",
    "## What is OpenSpiel?\n",
    "\n",
    "**OpenSpiel** is a library from DeepMind with **70+ game environments** for RL research.\n",
    "\n",
    "## OpenEnv's Integration\n",
    "\n",
    "We've wrapped **6 OpenSpiel games** following the OpenEnv pattern:\n",
    "\n",
    "<table>\n",
    "<tr>\n",
    "<td width=\"50%\">\n",
    "\n",
    "**🎯 Single-Player**\n",
    "1. **Catch** - Catch falling ball\n",
    "2. **Cliff Walking** - Navigate grid\n",
    "3. **2048** - Tile puzzle\n",
    "4. **Blackjack** - Card game\n",
    "\n",
    "</td>\n",
    "<td width=\"50%\">\n",
    "\n",
    "**👥 Multi-Player**\n",
    "5. **Tic-Tac-Toe** - Classic 3×3\n",
    "6. **Kuhn Poker** - Imperfect info poker\n",
    "\n",
    "</td>\n",
    "</tr>\n",
    "</table>\n",
    "\n",
    "This shows how OpenEnv can wrap **any** existing RL library!\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "======================================================================\n",
      "   🔌 HOW OPENENV WRAPS OPENSPIEL\n",
      "======================================================================\n",
      "\n",
      "class OpenSpielEnv(HTTPEnvClient[OpenSpielAction, OpenSpielObservation]):\n",
      "    \n",
      "    def _step_payload(self, action: OpenSpielAction) -> dict:\n",
      "        '''Convert typed action to JSON for HTTP'''\n",
      "        return {\n",
      "            \"action_id\": action.action_id,\n",
      "            \"game_name\": action.game_name,\n",
      "        }\n",
      "    \n",
      "    def _parse_result(self, payload: dict) -> StepResult:\n",
      "        '''Parse HTTP JSON response into typed observation'''\n",
      "        return StepResult(\n",
      "            observation=OpenSpielObservation(...),\n",
      "            reward=payload['reward'],\n",
      "            done=payload['done']\n",
      "        )\n",
      "\n",
      "\n",
      "──────────────────────────────────────────────────────────────────────\n",
      "\n",
      "✨ Usage (works for ALL OpenEnv environments):\n",
      "\n",
      "  env = OpenSpielEnv(base_url=\"http://localhost:8000\")\n",
      "  \n",
      "  result = env.reset()\n",
      "  # Returns StepResult[OpenSpielObservation] - Type safe!\n",
      "  \n",
      "  result = env.step(OpenSpielAction(action_id=2, game_name=\"catch\"))\n",
      "  # Type checker knows this is valid!\n",
      "  \n",
      "  state = env.state()\n",
      "  # Returns OpenSpielState\n",
      "\n",
      "──────────────────────────────────────────────────────────────────────\n",
      "\n",
      "🎯 This pattern works for ANY environment you want to wrap!\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from envs.openspiel_env.client import OpenSpielEnv\n",
    "\n",
    "print(\"=\"*70)\n",
    "print(\"   🔌 HOW OPENENV WRAPS OPENSPIEL\")\n",
    "print(\"=\"*70)\n",
    "\n",
    "print(\"\"\"\n",
    "class OpenSpielEnv(HTTPEnvClient[OpenSpielAction, OpenSpielObservation]):\n",
    "    \n",
    "    def _step_payload(self, action: OpenSpielAction) -> dict:\n",
    "        '''Convert typed action to JSON for HTTP'''\n",
    "        return {\n",
    "            \"action_id\": action.action_id,\n",
    "            \"game_name\": action.game_name,\n",
    "        }\n",
    "    \n",
    "    def _parse_result(self, payload: dict) -> StepResult:\n",
    "        '''Parse HTTP JSON response into typed observation'''\n",
    "        return StepResult(\n",
    "            observation=OpenSpielObservation(...),\n",
    "            reward=payload['reward'],\n",
    "            done=payload['done']\n",
    "        )\n",
    "\n",
    "\"\"\")\n",
    "\n",
    "print(\"─\" * 70)\n",
    "print(\"\\n✨ Usage (works for ALL OpenEnv environments):\")\n",
    "print(\"\"\"\n",
    "  env = OpenSpielEnv(base_url=\"http://localhost:8000\")\n",
    "  \n",
    "  result = env.reset()\n",
    "  # Returns StepResult[OpenSpielObservation] - Type safe!\n",
    "  \n",
    "  result = env.step(OpenSpielAction(action_id=2, game_name=\"catch\"))\n",
    "  # Type checker knows this is valid!\n",
    "  \n",
    "  state = env.state()\n",
    "  # Returns OpenSpielState\n",
    "\"\"\")\n",
    "\n",
    "print(\"─\" * 70)\n",
    "print(\"\\n🎯 This pattern works for ANY environment you want to wrap!\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "======================================================================\n",
      "   🎮 OPENSPIEL INTEGRATION - TYPE-SAFE MODELS\n",
      "======================================================================\n",
      "\n",
      "📤 OpenSpielAction (what you send):\n",
      "   ────────────────────────────────────────────────────────────────\n",
      "   • metadata             : typing.Dict[str, typing.Any]\n",
      "   • action_id            : int\n",
      "   • game_name            : str\n",
      "   • game_params          : Dict[str, Any]\n",
      "\n",
      "📥 OpenSpielObservation (what you receive):\n",
      "   ────────────────────────────────────────────────────────────────\n",
      "   • done                 : <class 'bool'>\n",
      "   • reward               : typing.Union[bool, int, float, NoneType]\n",
      "   • metadata             : typing.Dict[str, typing.Any]\n",
      "   • info_state           : List[float]\n",
      "   • legal_actions        : List[int]\n",
      "   • game_phase           : str\n",
      "   • current_player_id    : int\n",
      "   • opponent_last_action : Optional[int]\n",
      "\n",
      "📊 OpenSpielState (episode metadata):\n",
      "   ────────────────────────────────────────────────────────────────\n",
      "   • episode_id           : typing.Optional[str]\n",
      "   • step_count           : <class 'int'>\n",
      "   • game_name            : str\n",
      "   • agent_player         : int\n",
      "   • opponent_policy      : str\n",
      "   • game_params          : Dict[str, Any]\n",
      "   • num_players          : int\n",
      "\n",
      "======================================================================\n",
      "\n",
      "💡 Type safety means:\n",
      "   ✅ Your IDE autocompletes these fields\n",
      "   ✅ Typos are caught before running\n",
      "   ✅ Refactoring is safe\n",
      "   ✅ Self-documenting code\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Import OpenSpiel integration models\n",
    "from envs.openspiel_env.models import (\n",
    "    OpenSpielAction,\n",
    "    OpenSpielObservation,\n",
    "    OpenSpielState\n",
    ")\n",
    "from dataclasses import fields\n",
    "\n",
    "print(\"=\"*70)\n",
    "print(\"   🎮 OPENSPIEL INTEGRATION - TYPE-SAFE MODELS\")\n",
    "print(\"=\"*70)\n",
    "\n",
    "print(\"\\n📤 OpenSpielAction (what you send):\")\n",
    "print(\"   \" + \"─\" * 64)\n",
    "for field in fields(OpenSpielAction):\n",
    "    print(f\"   • {field.name:20s} : {field.type}\")\n",
    "\n",
    "print(\"\\n📥 OpenSpielObservation (what you receive):\")\n",
    "print(\"   \" + \"─\" * 64)\n",
    "for field in fields(OpenSpielObservation):\n",
    "    print(f\"   • {field.name:20s} : {field.type}\")\n",
    "\n",
    "print(\"\\n📊 OpenSpielState (episode metadata):\")\n",
    "print(\"   \" + \"─\" * 64)\n",
    "for field in fields(OpenSpielState):\n",
    "    print(f\"   • {field.name:20s} : {field.type}\")\n",
    "\n",
    "print(\"\\n\" + \"=\"*70)\n",
    "print(\"\\n💡 Type safety means:\")\n",
    "print(\"   ✅ Your IDE autocompletes these fields\")\n",
    "print(\"   ✅ Typos are caught before running\")\n",
    "print(\"   ✅ Refactoring is safe\")\n",
    "print(\"   ✅ Self-documenting code\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### How the Client Works\n",
    "\n",
    "<div style=\"background-color: rgba(128, 128, 128, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0; border: 1px solid rgba(128, 128, 128, 0.2);\">\n",
    "\n",
    "The client **inherits from HTTPEnvClient** and implements 3 methods:\n",
    "\n",
    "1. `_step_payload()` - Convert action → JSON\n",
    "2. `_parse_result()` - Parse JSON → typed observation  \n",
    "3. `_parse_state()` - Parse JSON → state\n",
    "\n",
    "That's it! The base class handles all HTTP communication.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "<div style=\"text-align: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; border-radius: 15px; margin: 30px 0;\">\n",
    "\n",
    "# 🎮 Part 6: Using Real OpenSpiel\n",
    "\n",
    "### Now let's USE a production environment!\n",
    "\n",
    "We'll play **Catch** using OpenEnv's **OpenSpiel integration** 🎯<br>\n",
    "This is a REAL environment running in production at companies!\n",
    "\n",
    "<br>\n",
    "\n",
    "**Get ready for:**\n",
    "- 🔌 Using existing environments (not building)\n",
    "- 🤖 Testing policies against real games\n",
    "- 📊 Live gameplay visualization\n",
    "- 🎯 Production-ready patterns\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The Game: Catch 🔴🏓\n",
    "\n",
    "<table>\n",
    "<tr>\n",
    "<td width=\"40%\" style=\"text-align: center;\">\n",
    "\n",
    "```\n",
    "⬜ ⬜ 🔴 ⬜ ⬜\n",
    "⬜ ⬜ ⬜ ⬜ ⬜\n",
    "⬜ ⬜ ⬜ ⬜ ⬜   Ball\n",
    "⬜ ⬜ ⬜ ⬜ ⬜\n",
    "⬜ ⬜ ⬜ ⬜ ⬜   falls\n",
    "⬜ ⬜ ⬜ ⬜ ⬜\n",
    "⬜ ⬜ ⬜ ⬜ ⬜   down\n",
    "⬜ ⬜ ⬜ ⬜ ⬜\n",
    "⬜ ⬜ ⬜ ⬜ ⬜\n",
    "⬜ ⬜ 🏓 ⬜ ⬜\n",
    "     Paddle\n",
    "```\n",
    "\n",
    "</td>\n",
    "<td width=\"60%\">\n",
    "\n",
    "**Rules:**\n",
    "- 10×5 grid\n",
    "- Ball falls from random column\n",
    "- Move paddle left/right to catch it\n",
    "\n",
    "**Actions:**\n",
    "- `0` = Move LEFT ⬅️\n",
    "- `1` = STAY 🛑\n",
    "- `2` = Move RIGHT ➡️\n",
    "\n",
    "**Reward:**\n",
    "- `+1` if caught 🎉\n",
    "- `0` if missed 😢\n",
    "\n",
    "</td>\n",
    "</tr>\n",
    "</table>\n",
    "\n",
    "<div style=\"background-color: rgba(128, 128, 128, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0; border: 1px solid rgba(128, 128, 128, 0.2);\">\n",
    "\n",
    "**🎯 Why Catch?**\n",
    "- Simple rules (easy to understand)\n",
    "- Fast episodes (~5 steps)\n",
    "- Clear success/failure\n",
    "- Part of OpenSpiel's 70+ games!\n",
    "\n",
    "**💡 The Big Idea:**\n",
    "Instead of building this from scratch, we'll USE OpenEnv's existing OpenSpiel integration. Same interface, but production-ready!\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "🎮 ================================================================ 🎮\n",
      "   ✅ Importing Real OpenSpiel Environment!\n",
      "🎮 ================================================================ 🎮\n",
      "\n",
      "📦 What we just imported:\n",
      "   • OpenSpielEnv - HTTP client for OpenSpiel games\n",
      "   • OpenSpielAction - Type-safe actions\n",
      "   • OpenSpielObservation - Type-safe observations\n",
      "   • OpenSpielState - Episode metadata\n",
      "\n",
      "📋 OpenSpielObservation fields:\n",
      "   ────────────────────────────────────────────────────────────\n",
      "   • done                      : <class 'bool'>\n",
      "   • reward                    : typing.Union[bool, int, float, NoneType]\n",
      "   • metadata                  : typing.Dict[str, typing.Any]\n",
      "   • info_state                : List[float]\n",
      "   • legal_actions             : List[int]\n",
      "   • game_phase                : str\n",
      "   • current_player_id         : int\n",
      "   • opponent_last_action      : Optional[int]\n",
      "\n",
      "======================================================================\n",
      "\n",
      "💡 This is REAL OpenEnv code - used in production!\n",
      "   • Wraps 6 OpenSpiel games (Catch, Tic-Tac-Toe, Poker, etc.)\n",
      "   • Type-safe actions and observations\n",
      "   • Works via HTTP (we'll see that next!)\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from envs.openspiel_env import OpenSpielEnv\n",
    "from envs.openspiel_env.models import (\n",
    "    OpenSpielAction,\n",
    "    OpenSpielObservation,\n",
    "    OpenSpielState\n",
    ")\n",
    "from dataclasses import fields\n",
    "\n",
    "print(\"🎮 \" + \"=\"*64 + \" 🎮\")\n",
    "print(\"   ✅ Importing Real OpenSpiel Environment!\")\n",
    "print(\"🎮 \" + \"=\"*64 + \" 🎮\\n\")\n",
    "\n",
    "print(\"📦 What we just imported:\")\n",
    "print(\"   • OpenSpielEnv - HTTP client for OpenSpiel games\")\n",
    "print(\"   • OpenSpielAction - Type-safe actions\")\n",
    "print(\"   • OpenSpielObservation - Type-safe observations\")\n",
    "print(\"   • OpenSpielState - Episode metadata\\n\")\n",
    "\n",
    "print(\"📋 OpenSpielObservation fields:\")\n",
    "print(\"   \" + \"─\" * 60)\n",
    "for field in fields(OpenSpielObservation):\n",
    "    print(f\"   • {field.name:25s} : {field.type}\")\n",
    "\n",
    "print(\"\\n\" + \"=\"*70)\n",
    "print(\"\\n💡 This is REAL OpenEnv code - used in production!\")\n",
    "print(\"   • Wraps 6 OpenSpiel games (Catch, Tic-Tac-Toe, Poker, etc.)\")\n",
    "print(\"   • Type-safe actions and observations\")\n",
    "print(\"   • Works via HTTP (we\\'ll see that next!)\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "🚀 ================================================================ 🚀\n",
      "   Starting OpenSpiel Server (Catch Game)\n",
      "🚀 ================================================================ 🚀\n",
      "\n",
      "⚠️  OpenSpiel not found. Installing...\n"
     ]
    },
    {
     "ename": "CalledProcessError",
     "evalue": "Command '['d:\\\\ANACONDA\\\\envs\\\\openenv\\\\python.exe', '-m', 'pip', 'install', '-q', 'open_spiel']' returned non-zero exit status 1.",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mModuleNotFoundError\u001B[0m                       Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[9], line 12\u001B[0m\n\u001B[0;32m     11\u001B[0m \u001B[38;5;28;01mtry\u001B[39;00m:\n\u001B[1;32m---> 12\u001B[0m     \u001B[38;5;28;01mimport\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;21;01mpyspiel\u001B[39;00m\n\u001B[0;32m     13\u001B[0m     \u001B[38;5;28mprint\u001B[39m(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m✅ OpenSpiel is installed!\u001B[39m\u001B[38;5;130;01m\\n\u001B[39;00m\u001B[38;5;124m\"\u001B[39m)\n",
      "\u001B[1;31mModuleNotFoundError\u001B[0m: No module named 'pyspiel'",
      "\nDuring handling of the above exception, another exception occurred:\n",
      "\u001B[1;31mCalledProcessError\u001B[0m                        Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[9], line 17\u001B[0m\n\u001B[0;32m     15\u001B[0m     \u001B[38;5;28mprint\u001B[39m(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m⚠️  OpenSpiel not found. Installing...\u001B[39m\u001B[38;5;124m\"\u001B[39m)\n\u001B[0;32m     16\u001B[0m     \u001B[38;5;28;01mimport\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[38;5;21;01msubprocess\u001B[39;00m\n\u001B[1;32m---> 17\u001B[0m     \u001B[43msubprocess\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mcheck_call\u001B[49m\u001B[43m(\u001B[49m\u001B[43m[\u001B[49m\u001B[43msys\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mexecutable\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43m-m\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43mpip\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43minstall\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43m-q\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43mopen_spiel\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m]\u001B[49m\u001B[43m)\u001B[49m\n\u001B[0;32m     18\u001B[0m     \u001B[38;5;28mprint\u001B[39m(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m✅ OpenSpiel installed!\u001B[39m\u001B[38;5;130;01m\\n\u001B[39;00m\u001B[38;5;124m\"\u001B[39m)\n\u001B[0;32m     20\u001B[0m \u001B[38;5;66;03m# Start the OpenSpiel server in background\u001B[39;00m\n",
      "File \u001B[1;32md:\\ANACONDA\\envs\\openenv\\Lib\\subprocess.py:413\u001B[0m, in \u001B[0;36mcheck_call\u001B[1;34m(*popenargs, **kwargs)\u001B[0m\n\u001B[0;32m    411\u001B[0m     \u001B[38;5;28;01mif\u001B[39;00m cmd \u001B[38;5;129;01mis\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m:\n\u001B[0;32m    412\u001B[0m         cmd \u001B[38;5;241m=\u001B[39m popenargs[\u001B[38;5;241m0\u001B[39m]\n\u001B[1;32m--> 413\u001B[0m     \u001B[38;5;28;01mraise\u001B[39;00m CalledProcessError(retcode, cmd)\n\u001B[0;32m    414\u001B[0m \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;241m0\u001B[39m\n",
      "\u001B[1;31mCalledProcessError\u001B[0m: Command '['d:\\\\ANACONDA\\\\envs\\\\openenv\\\\python.exe', '-m', 'pip', 'install', '-q', 'open_spiel']' returned non-zero exit status 1."
     ]
    }
   ],
   "source": [
    "import subprocess\n",
    "import time\n",
    "import sys\n",
    "import os\n",
    "\n",
    "print(\"🚀 \" + \"=\"*64 + \" 🚀\")\n",
    "print(\"   Starting OpenSpiel Server (Catch Game)\")\n",
    "print(\"🚀 \" + \"=\"*64 + \" 🚀\\n\")\n",
    "\n",
    "# Check if open_spiel is installed\n",
    "try:\n",
    "    import pyspiel\n",
    "    print(\"✅ OpenSpiel is installed!\\n\")\n",
    "except ImportError:\n",
    "    print(\"⚠️  OpenSpiel not found. Installing...\")\n",
    "    import subprocess\n",
    "    subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"open_spiel\"])\n",
    "    print(\"✅ OpenSpiel installed!\\n\")\n",
    "\n",
    "# Start the OpenSpiel server in background\n",
    "print(\"⚡ Starting FastAPI server for OpenSpiel Catch...\")\n",
    "print(\"   (This uses REAL OpenEnv + OpenSpiel integration)\\n\")\n",
    "\n",
    "# Determine the correct path\n",
    "if IN_COLAB:\n",
    "    work_dir = \"/content/OpenEnv\"\n",
    "else:\n",
    "    from pathlib import Path\n",
    "    work_dir = str(Path.cwd().parent.absolute())\n",
    "\n",
    "server_process = subprocess.Popen(\n",
    "    [sys.executable, \"-m\", \"uvicorn\",\n",
    "     \"envs.openspiel_env.server.app:app\",\n",
    "     \"--host\", \"0.0.0.0\",\n",
    "     \"--port\", \"8000\"],\n",
    "    env={**os.environ,\n",
    "         \"PYTHONPATH\": f\"{work_dir}/src\",\n",
    "         \"OPENSPIEL_GAME\": \"catch\",\n",
    "         \"OPENSPIEL_AGENT_PLAYER\": \"0\",\n",
    "         \"OPENSPIEL_OPPONENT_POLICY\": \"random\"},\n",
    "    stdout=subprocess.DEVNULL,\n",
    "    stderr=subprocess.DEVNULL,\n",
    "    text=True,\n",
    "    cwd=work_dir\n",
    ")\n",
    "\n",
    "# Wait for server to start\n",
    "print(\"⏳ Waiting for server to start...\")\n",
    "time.sleep(5)\n",
    "\n",
    "# Check if server is running\n",
    "import requests\n",
    "try:\n",
    "    response = requests.get('http://localhost:8000/health', timeout=2)\n",
    "    print(\"\\n✅ OpenSpiel server is running!\")\n",
    "    print(\"🌐 Server URL: http://localhost:8000\")\n",
    "    print(\"📍 Endpoints available:\")\n",
    "    print(\"   • POST /reset\")\n",
    "    print(\"   • POST /step\")\n",
    "    print(\"   • GET /state\")\n",
    "    print(\"\\n🎯 This is REAL OpenEnv + OpenSpiel in action!\")\n",
    "    print(\"   • Running actual OpenSpiel Catch game\")\n",
    "    print(\"   • Exposed via FastAPI HTTP server\")\n",
    "    print(\"   • Using OpenEnv's standard interface\\n\")\n",
    "except Exception as e:\n",
    "    print(f\"\\n❌ Server failed to start: {e}\")\n",
    "    print(\"\\n📋 Checking error output...\")\n",
    "    server_process.poll()\n",
    "    if server_process.stderr:\n",
    "        stderr = server_process.stderr.read()\n",
    "        if stderr:\n",
    "            print(stderr)\n",
    "    print(\"\\n💡 Make sure open_spiel is installed:\")\n",
    "    print(\"   pip install open_spiel\")\n",
    "    raise"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"📱 \" + \"=\"*64 + \" 📱\")\n",
    "print(\"   Connecting to OpenSpiel Server via HTTP\")\n",
    "print(\"📱 \" + \"=\"*64 + \" 📱\\n\")\n",
    "\n",
    "# Create HTTP client for OpenSpiel\n",
    "client = OpenSpielEnv(base_url=\"http://localhost:8000\")\n",
    "\n",
    "print(\"✅ Client created!\")\n",
    "print(\"\\n💡 What just happened:\")\n",
    "print(\"   • OpenSpielEnv is an HTTPEnvClient subclass\")\n",
    "print(\"   • It knows how to talk to OpenSpiel servers\")\n",
    "print(\"   • All communication is type-safe and over HTTP\")\n",
    "print(\"   • Same client works for ALL OpenSpiel games!\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"🎮 \" + \"=\"*64 + \" 🎮\")\n",
    "print(\"   Testing Connection - Playing One Step\")\n",
    "print(\"🎮 \" + \"=\"*64 + \" 🎮\\n\")\n",
    "\n",
    "# Reset the environment (HTTP POST /reset)\n",
    "print(\"📤 Calling client.reset()...\")\n",
    "print(\"   Under the hood: HTTP POST to http://localhost:8000/reset\\n\")\n",
    "\n",
    "result = client.reset()\n",
    "\n",
    "print(\"📥 Received OpenSpielObservation:\")\n",
    "print(f\"   • info_state: {result.observation.info_state[:10]}... (first 10 values)\")\n",
    "print(f\"   • number of info_state: {len(result.observation.info_state)}\")\n",
    "print(f\"   • legal_actions: {result.observation.legal_actions}\")\n",
    "print(f\"   • game_phase: {result.observation.game_phase}\")\n",
    "print(f\"   • done: {result.done}\")\n",
    "\n",
    "# Take an action (HTTP POST /step)\n",
    "print(\"\\n📤 Calling client.step(OpenSpielAction(action_id=1, game_name=\\'catch\\'))...\")\n",
    "print(\"   Under the hood: HTTP POST to http://localhost:8000/step\\n\")\n",
    "\n",
    "action = OpenSpielAction(action_id=1, game_name=\"catch\")  # STAY\n",
    "result = client.step(action)\n",
    "\n",
    "print(\"📥 Received response:\")\n",
    "print(f\"   • Reward: {result.reward}\")\n",
    "print(f\"   • Done: {result.done}\")\n",
    "print(f\"   • legal_actions: {result.observation.legal_actions}\")\n",
    "\n",
    "# Get state (HTTP GET /state)\n",
    "state = client.state()\n",
    "print(f\"\\n📊 Episode state:\")\n",
    "print(f\"   • episode_id: {state.episode_id}\")\n",
    "print(f\"   • step_count: {state.step_count}\")\n",
    "print(f\"   • game_name: {state.game_name}\")\n",
    "\n",
    "print(\"\\n\" + \"=\"*70)\n",
    "print(\"\\n🎉 IT WORKS! We\\'re using REAL OpenSpiel via HTTP!\")\n",
    "print(\"   ✅ Type-safe communication\")\n",
    "print(\"   ✅ Same interface as any OpenEnv environment\")\n",
    "print(\"   ✅ Production-ready architecture\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "# Part 7: Four Policies 🤖\n",
    "\n",
    "<div style=\"background-color: #f8f9fa; padding: 20px; border-radius: 10px; margin: 20px 0;\">\n",
    "\n",
    "## Let's test 4 different AI strategies:\n",
    "\n",
    "<table>\n",
    "<tr>\n",
    "<th width=\"25%\">Policy</th>\n",
    "<th width=\"50%\">Strategy</th>\n",
    "<th width=\"25%\">Expected Performance</th>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>🎲 Random</b></td>\n",
    "<td>Pick random action every step</td>\n",
    "<td>~20% (pure luck)</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>🛑 Always Stay</b></td>\n",
    "<td>Never move, hope ball lands in center</td>\n",
    "<td>~20% (terrible!)</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>🧠 Smart</b></td>\n",
    "<td>Move paddle toward ball</td>\n",
    "<td>100% (optimal!)</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>📈 Learning</b></td>\n",
    "<td>Start random, learn smart strategy</td>\n",
    "<td>~85% (improves over time)</td>\n",
    "</tr>\n",
    "</table>\n",
    "\n",
    "**💡 These policies work with ANY OpenSpiel game!**\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "\n",
    "# ============================================================================\n",
    "# POLICIES - Different AI strategies (adapted for OpenSpiel)\n",
    "# ============================================================================\n",
    "\n",
    "class RandomPolicy:\n",
    "    \"\"\"Baseline: Pure random guessing.\"\"\"\n",
    "    name = \"🎲 Random Guesser\"\n",
    "\n",
    "    def select_action(self, obs: OpenSpielObservation) -> int:\n",
    "        return random.choice(obs.legal_actions)\n",
    "\n",
    "\n",
    "class AlwaysStayPolicy:\n",
    "    \"\"\"Bad strategy: Never moves.\"\"\"\n",
    "    name = \"🛑 Always Stay\"\n",
    "\n",
    "    def select_action(self, obs: OpenSpielObservation) -> int:\n",
    "        return 1  # STAY\n",
    "\n",
    "\n",
    "class SmartPolicy:\n",
    "    \"\"\"Optimal: Move paddle toward ball.\"\"\"\n",
    "    name = \"🧠 Smart Heuristic\"\n",
    "\n",
    "    def select_action(self, obs: OpenSpielObservation) -> int:\n",
    "        # Parse OpenSpiel observation\n",
    "        # For Catch: info_state is a flattened 10x5 grid\n",
    "        # Ball position and paddle position encoded in the vector\n",
    "        info_state = obs.info_state\n",
    "\n",
    "        # Find ball and paddle positions from info_state\n",
    "        # Catch uses a 10x5 grid, so 50 values\n",
    "        grid_size = 5\n",
    "\n",
    "        # Find positions (ball = 1.0 in the flattened grid, paddle = 1.0 in the last row of the flattened grid)\n",
    "        ball_col = None\n",
    "        paddle_col = None\n",
    "\n",
    "        for idx, val in enumerate(info_state):\n",
    "            if abs(val - 1.0) < 0.01:  # Ball\n",
    "                ball_col = idx % grid_size\n",
    "                break\n",
    "\n",
    "        last_row = info_state[-grid_size:]\n",
    "        paddle_col = last_row.index(1.0) # Paddle\n",
    "\n",
    "        if ball_col is not None and paddle_col is not None:\n",
    "            if paddle_col < ball_col:\n",
    "                return 2  # Move RIGHT\n",
    "            elif paddle_col > ball_col:\n",
    "                return 0  # Move LEFT\n",
    "\n",
    "        return 1  # STAY (fallback)\n",
    "\n",
    "\n",
    "class LearningPolicy:\n",
    "    \"\"\"Simulated RL: Epsilon-greedy exploration.\"\"\"\n",
    "    name = \"📈 Learning Agent\"\n",
    "\n",
    "    def __init__(self):\n",
    "        self.steps = 0\n",
    "        self.smart_policy = SmartPolicy()\n",
    "\n",
    "    def select_action(self, obs: OpenSpielObservation) -> int:\n",
    "        self.steps += 1\n",
    "\n",
    "        # Decay exploration rate over time\n",
    "        epsilon = max(0.1, 1.0 - (self.steps / 100))\n",
    "\n",
    "        if random.random() < epsilon:\n",
    "            # Explore: random action\n",
    "            return random.choice(obs.legal_actions)\n",
    "        else:\n",
    "            # Exploit: use smart strategy\n",
    "            return self.smart_policy.select_action(obs)\n",
    "\n",
    "\n",
    "print(\"🤖 \" + \"=\"*64 + \" 🤖\")\n",
    "print(\"   ✅ 4 Policies Created (Adapted for OpenSpiel)!\")\n",
    "print(\"🤖 \" + \"=\"*64 + \" 🤖\\n\")\n",
    "\n",
    "policies = [RandomPolicy(), AlwaysStayPolicy(), SmartPolicy(), LearningPolicy()]\n",
    "for i, policy in enumerate(policies, 1):\n",
    "    print(f\"   {i}. {policy.name}\")\n",
    "\n",
    "print(\"\\n💡 These policies work with OpenSpielObservation!\")\n",
    "print(\"   • Read info_state (flattened grid)\")\n",
    "print(\"   • Use legal_actions\")\n",
    "print(\"   • Work with ANY OpenSpiel game that exposes these!\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Watch a Policy Play!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "def run_episode(env, policy, visualize=True, delay=0.3):\n",
    "    \"\"\"Run one episode with a policy against OpenSpiel environment.\"\"\"\n",
    "\n",
    "    # RESET\n",
    "    result = env.reset()\n",
    "    obs = result.observation\n",
    "\n",
    "    if visualize:\n",
    "        print(f\"\\n{'='*60}\")\n",
    "        print(f\"   🎮 {policy.name}\")\n",
    "        print(f\"   🎲 Playing against OpenSpiel Catch\")\n",
    "        print('='*60 + '\\n')\n",
    "        time.sleep(delay)\n",
    "\n",
    "    total_reward = 0\n",
    "    step = 0\n",
    "    action_names = [\"⬅️  LEFT\", \"🛑 STAY\", \"➡️  RIGHT\"]\n",
    "\n",
    "    # THE RL LOOP\n",
    "    while not obs.done:\n",
    "        # 1. Policy chooses action\n",
    "        action_id = policy.select_action(obs)\n",
    "\n",
    "        # 2. Environment executes (via HTTP!)\n",
    "        action = OpenSpielAction(action_id=action_id, game_name=\"catch\")\n",
    "        result = env.step(action)\n",
    "        obs = result.observation\n",
    "\n",
    "        # 3. Collect reward\n",
    "        if result.reward is not None:\n",
    "            total_reward += result.reward\n",
    "\n",
    "        if visualize:\n",
    "            print(f\"📍 Step {step + 1}: {action_names[action_id]} → Reward: {result.reward}\")\n",
    "            time.sleep(delay)\n",
    "\n",
    "        step += 1\n",
    "\n",
    "    if visualize:\n",
    "        result_text = \"🎉 CAUGHT!\" if total_reward > 0 else \"😢 MISSED\"\n",
    "        print(f\"\\n{'='*60}\")\n",
    "        print(f\"   {result_text} Total Reward: {total_reward}\")\n",
    "        print('='*60)\n",
    "\n",
    "    return total_reward > 0\n",
    "\n",
    "\n",
    "print(\"📺 \" + \"=\"*64 + \" 📺\")\n",
    "print(\"   Watch Smart Policy Play Against OpenSpiel!\")\n",
    "print(\"📺 \" + \"=\"*64 + \" 📺\\n\")\n",
    "\n",
    "# Demo: Watch Smart Policy in action\n",
    "policy = SmartPolicy()\n",
    "run_episode(client, policy, visualize=True, delay=0.5)\n",
    "\n",
    "print(\"\\n💡 You just watched REAL OpenSpiel Catch being played!\")\n",
    "print(\"   • Every action was an HTTP call\")\n",
    "print(\"   • Game logic runs in the server\")\n",
    "print(\"   • Client only sends actions and receives observations\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "# Part 8: Policy Competition! 🏆\n",
    "\n",
    "<div style=\"background-color: rgba(3, 102, 214, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0;\">\n",
    "\n",
    "Let's run **50 episodes** for each policy against **REAL OpenSpiel** and see who wins!\n",
    "\n",
    "This is production code - every action is an HTTP call to the OpenSpiel server!\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def evaluate_policies(env, num_episodes=50):\n",
    "    \"\"\"Compare all policies over many episodes using real OpenSpiel.\"\"\"\n",
    "    policies = [\n",
    "        RandomPolicy(),\n",
    "        AlwaysStayPolicy(),\n",
    "        SmartPolicy(),\n",
    "        LearningPolicy(),\n",
    "    ]\n",
    "\n",
    "    print(\"\\n🏆 \" + \"=\"*66 + \" 🏆\")\n",
    "    print(f\"   POLICY SHOWDOWN - {num_episodes} Episodes Each\")\n",
    "    print(f\"   Playing against REAL OpenSpiel Catch!\")\n",
    "    print(\"🏆 \" + \"=\"*66 + \" 🏆\\n\")\n",
    "\n",
    "    results = []\n",
    "    for policy in policies:\n",
    "        print(f\"⚡ Testing {policy.name}...\", end=\" \")\n",
    "        successes = sum(run_episode(env, policy, visualize=False)\n",
    "                       for _ in range(num_episodes))\n",
    "        success_rate = (successes / num_episodes) * 100\n",
    "        results.append((policy.name, success_rate, successes))\n",
    "        print(f\"✓ Done!\")\n",
    "\n",
    "    print(\"\\n\" + \"=\"*70)\n",
    "    print(\"   📊 FINAL RESULTS\")\n",
    "    print(\"=\"*70 + \"\\n\")\n",
    "\n",
    "    # Sort by success rate (descending)\n",
    "    results.sort(key=lambda x: x[1], reverse=True)\n",
    "\n",
    "    # Award medals to top 3\n",
    "    medals = [\"🥇\", \"🥈\", \"🥉\", \"  \"]\n",
    "\n",
    "    for i, (name, rate, successes) in enumerate(results):\n",
    "        medal = medals[i]\n",
    "        bar = \"█\" * int(rate / 2)\n",
    "        print(f\"{medal} {name:25s} [{bar:<50}] {rate:5.1f}% ({successes}/{num_episodes})\")\n",
    "\n",
    "    print(\"\\n\" + \"=\"*70)\n",
    "    print(\"\\n✨ Key Insights:\")\n",
    "    print(\"   • Random (~20%):      Baseline - pure luck 🎲\")\n",
    "    print(\"   • Always Stay (~20%): Bad strategy - stays center 🛑\")\n",
    "    print(\"   • Smart (100%):       Optimal - perfect play! 🧠\")\n",
    "    print(\"   • Learning (~85%):    Improves over time 📈\")\n",
    "    print(\"\\n🎓 This is Reinforcement Learning + OpenEnv in action:\")\n",
    "    print(\"   1. We USED existing OpenSpiel environment (didn\\'t build it)\")\n",
    "    print(\"   2. Type-safe communication over HTTP\")\n",
    "    print(\"   3. Same code works for ANY OpenSpiel game\")\n",
    "    print(\"   4. Production-ready architecture\\n\")\n",
    "\n",
    "# Run the epic competition!\n",
    "print(\"🎮 Starting the showdown against REAL OpenSpiel...\\n\")\n",
    "evaluate_policies(client, num_episodes=50)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "<a id=\"part-9\"></a>\n",
    "# Part 9: Switching to Other Games 🎮\n",
    "\n",
    "<div style=\"background-color: rgba(40, 167, 69, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0;\">\n",
    "\n",
    "## What We Just Used: Real OpenSpiel! 🎉\n",
    "\n",
    "In Parts 6-8, we **USED** the existing OpenSpiel Catch environment:\n",
    "\n",
    "<table>\n",
    "<tr>\n",
    "<th>What We Did</th>\n",
    "<th>How It Works</th>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Imported</b></td>\n",
    "<td>OpenSpielEnv client (pre-built)</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Started</b></td>\n",
    "<td>OpenSpiel server via uvicorn</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Connected</b></td>\n",
    "<td>HTTP client to server</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Played</b></td>\n",
    "<td>Real OpenSpiel Catch game</td>\n",
    "</tr>\n",
    "</table>\n",
    "\n",
    "**🎯 This is production code!** Every action was an HTTP call to a real OpenSpiel environment.\n",
    "\n",
    "</div>\n",
    "\n",
    "## 🎮 6 Games Available - Same Interface!\n",
    "\n",
    "The beauty of OpenEnv? **Same code, different games!**\n",
    "\n",
    "```python\n",
    "# We just used Catch\n",
    "env = OpenSpielEnv(base_url=\"http://localhost:8000\")\n",
    "# game_name=\"catch\" was set via environment variable\n",
    "\n",
    "# Want Tic-Tac-Toe instead? Just change the game!\n",
    "# Start server with: OPENSPIEL_GAME=tic_tac_toe uvicorn ...\n",
    "# Same client code works!\n",
    "```\n",
    "\n",
    "<div style=\"background-color: rgba(255, 152, 0, 0.1); padding: 15px; border-radius: 5px; margin: 20px 0;\">\n",
    "\n",
    "**🎮 All 6 Games:**\n",
    "\n",
    "1. ✅ **`catch`** - What we just used!\n",
    "2. **`tic_tac_toe`** - Classic 3×3\n",
    "3. **`kuhn_poker`** - Imperfect information poker\n",
    "4. **`cliff_walking`** - Grid navigation\n",
    "5. **`2048`** - Tile puzzle\n",
    "6. **`blackjack`** - Card game\n",
    "\n",
    "**All use the exact same OpenSpielEnv client!**\n",
    "\n",
    "</div>\n",
    "\n",
    "### Try Another Game (Optional):\n",
    "\n",
    "```python\n",
    "# Stop the current server (kill the server_process)\n",
    "# Then start a new game:\n",
    "\n",
    "server_process = subprocess.Popen(\n",
    "    [sys.executable, \"-m\", \"uvicorn\",\n",
    "     \"envs.openspiel_env.server.app:app\",\n",
    "     \"--host\", \"0.0.0.0\",\n",
    "     \"--port\", \"8000\"],\n",
    "    env={**os.environ,\n",
    "         \"PYTHONPATH\": f\"{work_dir}/src\",\n",
    "         \"OPENSPIEL_GAME\": \"tic_tac_toe\",  # Changed!\n",
    "         \"OPENSPIEL_AGENT_PLAYER\": \"0\",\n",
    "         \"OPENSPIEL_OPPONENT_POLICY\": \"random\"},\n",
    "    # ... rest of config\n",
    ")\n",
    "\n",
    "# Same client works!\n",
    "client = OpenSpielEnv(base_url=\"http://localhost:8000\")\n",
    "result = client.reset()  # Now playing Tic-Tac-Toe!\n",
    "```\n",
    "\n",
    "**💡 Key Insight**: You don't rebuild anything - you just USE different games with the same client!\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "<a id=\"part-10\"></a>\n",
    "# Part 10: Create Your Own Integration 🛠️\n",
    "\n",
    "<div style=\"background-color: rgba(3, 102, 214, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0;\">\n",
    "\n",
    "## The 5-Step Pattern\n",
    "\n",
    "Want to wrap your own environment in OpenEnv? Here's how:\n",
    "\n",
    "</div>\n",
    "\n",
    "### Step 1: Define Types (`models.py`)\n",
    "\n",
    "```python\n",
    "from dataclasses import dataclass\n",
    "from core.env_server import Action, Observation, State\n",
    "\n",
    "@dataclass\n",
    "class YourAction(Action):\n",
    "    action_value: int\n",
    "    # Add your action fields\n",
    "\n",
    "@dataclass\n",
    "class YourObservation(Observation):\n",
    "    state_data: List[float]\n",
    "    done: bool\n",
    "    reward: float\n",
    "    # Add your observation fields\n",
    "\n",
    "@dataclass\n",
    "class YourState(State):\n",
    "    episode_id: str\n",
    "    step_count: int\n",
    "    # Add your state fields\n",
    "```\n",
    "\n",
    "### Step 2: Implement Environment (`server/environment.py`)\n",
    "\n",
    "```python\n",
    "from core.env_server import Environment\n",
    "\n",
    "class YourEnvironment(Environment):\n",
    "    def reset(self) -> Observation:\n",
    "        # Initialize your game/simulation\n",
    "        return YourObservation(...)\n",
    "    \n",
    "    def step(self, action: Action) -> Observation:\n",
    "        # Execute action, update state\n",
    "        return YourObservation(...)\n",
    "    \n",
    "    @property\n",
    "    def state(self) -> State:\n",
    "        return self._state\n",
    "```\n",
    "\n",
    "### Step 3: Create Client (`client.py`)\n",
    "\n",
    "```python\n",
    "from core.http_env_client import HTTPEnvClient\n",
    "from core.types import StepResult\n",
    "\n",
    "class YourEnv(HTTPEnvClient[YourAction, YourObservation]):\n",
    "    def _step_payload(self, action: YourAction) -> dict:\n",
    "        \"\"\"Convert action to JSON\"\"\"\n",
    "        return {\"action_value\": action.action_value}\n",
    "    \n",
    "    def _parse_result(self, payload: dict) -> StepResult:\n",
    "        \"\"\"Parse JSON to observation\"\"\"\n",
    "        return StepResult(\n",
    "            observation=YourObservation(...),\n",
    "            reward=payload['reward'],\n",
    "            done=payload['done']\n",
    "        )\n",
    "    \n",
    "    def _parse_state(self, payload: dict) -> YourState:\n",
    "        return YourState(...)\n",
    "```\n",
    "\n",
    "### Step 4: Create Server (`server/app.py`)\n",
    "\n",
    "```python\n",
    "from core.env_server import create_fastapi_app\n",
    "from .your_environment import YourEnvironment\n",
    "\n",
    "env = YourEnvironment()\n",
    "app = create_fastapi_app(env)\n",
    "\n",
    "# That's it! OpenEnv creates all endpoints for you.\n",
    "```\n",
    "\n",
    "### Step 5: Dockerize (`server/Dockerfile`)\n",
    "\n",
    "```dockerfile\n",
    "FROM python:3.11-slim\n",
    "\n",
    "WORKDIR /app\n",
    "COPY requirements.txt .\n",
    "RUN pip install --no-cache-dir -r requirements.txt\n",
    "\n",
    "COPY . .\n",
    "CMD [\"uvicorn\", \"app:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\"]\n",
    "```\n",
    "\n",
    "<div style=\"background-color: rgba(40, 167, 69, 0.1); padding: 20px; border-left: 5px solid #28a745; margin: 20px 0;\">\n",
    "\n",
    "### 🎓 Examples to Study\n",
    "\n",
    "OpenEnv includes 3 complete examples:\n",
    "\n",
    "1. **`src/envs/echo_env/`**\n",
    "   - Simplest possible environment\n",
    "   - Great for testing and learning\n",
    "\n",
    "2. **`src/envs/openspiel_env/`**\n",
    "   - Wraps external library (OpenSpiel)\n",
    "   - Shows integration pattern\n",
    "   - 6 games in one integration\n",
    "\n",
    "3. **`src/envs/coding_env/`**\n",
    "   - Python code execution environment\n",
    "   - Shows complex use case\n",
    "   - Security considerations\n",
    "\n",
    "**💡 Study these to understand the patterns!**\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "<div style=\"background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 40px; border-radius: 15px; margin: 40px 0; text-align: center;\">\n",
    "\n",
    "# 🎓 Summary: Your Journey\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## What You Learned\n",
    "\n",
    "<table>\n",
    "<tr>\n",
    "<td width=\"50%\" style=\"vertical-align: top;\">\n",
    "\n",
    "### 📚 Concepts\n",
    "\n",
    "✅ **RL Fundamentals**\n",
    "- The observe-act-reward loop\n",
    "- What makes good policies\n",
    "- Exploration vs exploitation\n",
    "\n",
    "✅ **OpenEnv Architecture**\n",
    "- Client-server separation\n",
    "- Type-safe contracts\n",
    "- HTTP communication layer\n",
    "\n",
    "✅ **Production Patterns**\n",
    "- Docker isolation\n",
    "- API design\n",
    "- Reproducible deployments\n",
    "\n",
    "</td>\n",
    "<td width=\"50%\" style=\"vertical-align: top;\">\n",
    "\n",
    "### 🛠️ Skills\n",
    "\n",
    "✅ **Using Environments**\n",
    "- Import OpenEnv clients\n",
    "- Call reset/step/state\n",
    "- Work with typed observations\n",
    "\n",
    "✅ **Building Environments**\n",
    "- Define type-safe models\n",
    "- Implement Environment class\n",
    "- Create HTTPEnvClient\n",
    "\n",
    "✅ **Testing & Debugging**\n",
    "- Compare policies\n",
    "- Visualize episodes\n",
    "- Measure performance\n",
    "\n",
    "</td>\n",
    "</tr>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## OpenEnv vs Traditional RL\n",
    "\n",
    "<table>\n",
    "<tr>\n",
    "<th>Feature</th>\n",
    "<th>Traditional (Gym)</th>\n",
    "<th>OpenEnv</th>\n",
    "<th>Winner</th>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Type Safety</b></td>\n",
    "<td>❌ Arrays, dicts</td>\n",
    "<td>✅ Dataclasses</td>\n",
    "<td>🏆 OpenEnv</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Isolation</b></td>\n",
    "<td>❌ Same process</td>\n",
    "<td>✅ Docker</td>\n",
    "<td>🏆 OpenEnv</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Deployment</b></td>\n",
    "<td>❌ Manual setup</td>\n",
    "<td>✅ K8s-ready</td>\n",
    "<td>🏆 OpenEnv</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Language</b></td>\n",
    "<td>❌ Python only</td>\n",
    "<td>✅ Any (HTTP)</td>\n",
    "<td>🏆 OpenEnv</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Reproducibility</b></td>\n",
    "<td>❌ \"Works on my machine\"</td>\n",
    "<td>✅ Same everywhere</td>\n",
    "<td>🏆 OpenEnv</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td><b>Community</b></td>\n",
    "<td>✅ Large ecosystem</td>\n",
    "<td>🟡 Growing</td>\n",
    "<td>🤝 Both!</td>\n",
    "</tr>\n",
    "</table>\n",
    "\n",
    "<div style=\"background-color: rgba(3, 102, 214, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0;\">\n",
    "\n",
    "**🎯 The Bottom Line**\n",
    "\n",
    "OpenEnv brings **production engineering** to RL:\n",
    "- Same environments work locally and in production\n",
    "- Type safety catches bugs early\n",
    "- Docker isolation prevents conflicts\n",
    "- HTTP API works with any language\n",
    "\n",
    "**It's RL for 2024 and beyond.**\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"resources\"></a>\n",
    "## 📚 Resources\n",
    "\n",
    "<div style=\"background-color: rgba(128, 128, 128, 0.1); padding: 20px; border-radius: 10px; margin: 20px 0; border: 1px solid rgba(128, 128, 128, 0.2);\">\n",
    "\n",
    "### 🔗 Essential Links\n",
    "\n",
    "- **🏠 OpenEnv GitHub**: https://github.com/meta-pytorch/OpenEnv\n",
    "- **🎮 OpenSpiel**: https://github.com/google-deepmind/open_spiel\n",
    "- **⚡ FastAPI Docs**: https://fastapi.tiangolo.com/\n",
    "- **🐳 Docker Guide**: https://docs.docker.com/get-started/\n",
    "- **🔥 PyTorch**: https://pytorch.org/\n",
    "\n",
    "### 📖 Documentation Deep Dives\n",
    "\n",
    "- **Environment Creation Guide**: `src/envs/README.md`\n",
    "- **OpenSpiel Integration**: `src/envs/openspiel_env/README.md`\n",
    "- **Example Scripts**: `examples/`\n",
    "- **RFC 001**: [Baseline API Specs](https://github.com/meta-pytorch/OpenEnv/pull/26)\n",
    "\n",
    "### 🎓 Community & Support\n",
    "\n",
    "**Supported by amazing organizations:**\n",
    "- 🔥 Meta PyTorch\n",
    "- 🤗 Hugging Face\n",
    "- ⚡ Unsloth AI\n",
    "- 🌟 Reflection AI\n",
    "- 🚀 And many more!\n",
    "\n",
    "**License**: BSD 3-Clause (very permissive!)\n",
    "\n",
    "**Contributions**: Always welcome! Check out the issues tab.\n",
    "\n",
    "</div>\n",
    "\n",
    "---\n",
    "\n",
    "### 🌈 What's Next?\n",
    "\n",
    "1. ⭐ **Star the repo** to show support and stay updated\n",
    "2. 🔄 **Try modifying** the Catch game (make it harder? bigger grid?)\n",
    "3. 🎮 **Explore** other OpenSpiel games\n",
    "4. 🛠️ **Build** your own environment integration\n",
    "5. 💬 **Share** what you build with the community!"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "openenv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
